package com.sikadwafastdaisfondturbo.pretloan.ui.process.activity

import android.os.Handler
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.ProcessStepAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.ActivityProcessBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.activity.ApplyActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.permission.PermissionUtils
import com.sikadwafastdaisfondturbo.pretloan.ui.process.page.BindAccountPage
import com.sikadwafastdaisfondturbo.pretloan.ui.process.page.CommonPage
import com.sikadwafastdaisfondturbo.pretloan.ui.process.page.ContactPage
import com.sikadwafastdaisfondturbo.pretloan.ui.process.page.FacePage
import com.sikadwafastdaisfondturbo.pretloan.ui.process.page.OcrPage
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.SikadwaPickContactUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/23 10:43
 * @Annotation：流程列表页面
 */
class ProcessActivity : ProActivity() {
    lateinit var binding: ActivityProcessBinding
    //选择联系人
    var pickContact: SikadwaPickContactUtils? = null

    //流程数据
    private var mStepData: JSONObject? = null
    private var mTabAdapter: ProcessStepAdapter? = null
    override fun getRootView(): View {
        binding = ActivityProcessBinding.inflate(layoutInflater)
        return binding.root
    }

    @Subscribe
    override fun initView() {
        binding.parentLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        EventBus.getDefault().register(this)
        initRecyclerView()

        pickContact = SikadwaPickContactUtils(this)
    }

    override fun initListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }
        //联系客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("Information Process " + binding.textTitle.text.toString() + " Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER, "Information Process " + binding.textTitle.text.toString() + " Page")
        }
    }

    override fun initData() {
        loadProcessStepAction()
    }

    /* 权限请求监听 */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtils.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
    }

    /**
     * 初始化Tab列表
     */
    private fun initRecyclerView() {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.rvStep.layoutManager = layoutManager
        mTabAdapter = ProcessStepAdapter(binding.rvStep)
        binding.rvStep.adapter = mTabAdapter!!
        binding.rvStep.itemAnimator = DefaultItemAnimator()
        mTabAdapter!!.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
        })
    }

    /**
     * 显示全部流程列表
     */
    private fun setProcessTabList(dataList: ArrayList<JSONObject>, selectIndex: Int) {
        mTabAdapter!!.data = dataList
        if (selectIndex != -1) {
            binding.textTitle.text = dataList[selectIndex].optString("tabTitle")
            binding.rvStep.post {
                binding.rvStep.smoothScrollToPosition(selectIndex)
            }
        }
    }

    /**
     * 常规通用样式
     */
    private fun showCommonPage(data: JSONObject) {
        replaceContainerFragement(R.id.contentLayout, CommonPage(data))
    }

    /**
     * Contact联系人样式
     */
    private fun showContactInfoPage(data: JSONObject) {
        replaceContainerFragement(R.id.contentLayout, ContactPage(this,data))
    }

    /**
     * 证件照样式
     */
    private fun showOcrInfoPage() {
        replaceContainerFragement(R.id.contentLayout, OcrPage())
    }

    /**
     * 人脸自拍样式
     */
    private fun showSelfieInfoPage() {
        replaceContainerFragement(R.id.contentLayout, FacePage())
    }

    /**
     * 绑定账号（法语）
     */
    private fun showAccountInfoFrenchPage() {
        replaceContainerFragement(R.id.contentLayout, BindAccountPage())
    }

    /**
     * 进入贷款申请页面
     */
    private fun showApplyPage() {
        onIntent(ApplyActivity::class.java)
        Handler().postDelayed({
            finish()
        }, 500)
    }

    /**
     * 提交流程数据
     */
    fun submitAction(params: JSONObject) {
        showLoading()
        onSubmitProcessAction(params)
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    fun showSubmitSuccess() {
        //通知刷新总流程
        EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshedProcess(event: String){
        when(event){
            Configs.Event.PROCESS_REFRESHED -> {//总流程刷新完成
                loadProcessStepAction()
            }
        }
    }

    /**
     * 获取 steps 中第一个在步骤在总步骤中是第几个
     */
    private fun getStepIndex(): Int{
        var index = -1
        //剩余未完成步骤
        val steps = mStepData!!.optJSONArray("steps")
        if (steps == null || steps.length() == 0){//已完成
            return index
        }
        //总步骤
        val allSteps = mStepData!!.optJSONArray("allSteps") ?: return index

        //当前进行的步骤
        val curtStep = steps.optString(0)
        for (i in 0..<allSteps.length()){
            if (curtStep == allSteps.optString(i)){
                index = i
                break
            }
        }
        return index
    }

    /**
     * 获取流程步骤列表
     */
    private fun loadProcessStepAction(){
        mStepData = JSONObject(Configs.getSPString(Configs.SPKEY.SIKADWA_PROCESS))
        val allStepTitles = mStepData!!.optJSONArray("allStepTitles")
        val tabList = arrayListOf<JSONObject>()
        //当前进行的步骤
        val curtIndex = getStepIndex()
        for (i in 0 until allStepTitles!!.length()) {
            val tabObj = JSONObject()
            tabObj.put("tabTitle", allStepTitles.optString(i))
            tabObj.put("selectIndex", curtIndex)
            tabList.add(tabObj)
        }
        //设置所有步骤列表
        setProcessTabList(tabList,curtIndex)
        showStepPage()
    }

    /**
     * 根据Step类型显示不同的Page
     */
    private fun showStepPage(){
        //当前进行的步骤
        val curtIndex = getStepIndex()
        val allSteps = mStepData!!.optJSONArray("allSteps")
        if (curtIndex == -1){//所有步骤已完成
            showApplyPage()
            return
        }
        //获取对应的key
        val curtKey = allSteps?.optString(curtIndex)
        //Contact 类型
        if (mStepData!!.has(curtKey)){
            val stepData = mStepData!!.optJSONObject(curtKey)
            stepData?.put("stepTitle",curtKey)
            if (stepData != null && stepData.has("isContact") && stepData.optString("isContact") == "YES"){
                showContactInfoPage(stepData)
                return
            }
        }

        //todo Ocr证件照样式
        if (curtKey!!.contains("ocr_info")){
            showOcrInfoPage()
            return
        }

        //todo Selfie自拍照样式
        if (curtKey.contains("sefie_info")){
            showSelfieInfoPage()
            return
        }

        //todo Account账户样式（法语地区绑定账号）
        if (curtKey.contains("account_info") && Configs.isFrench()){
            showAccountInfoFrenchPage()
            return
        }
        //常规通用样式
        if (mStepData!!.has(curtKey)){
            val stepData = mStepData!!.optJSONObject(curtKey)
            stepData?.put("stepTitle",curtKey)
            showCommonPage(stepData)
        }
    }

    /**
     * 提交流程数据
     */
    private fun onSubmitProcessAction(params: JSONObject) {
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                showSubmitSuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}